<script setup lang="ts">
import { reactive, onMounted, ref, computed } from 'vue'
import { NIcon, NInput, NButton } from 'naive-ui'
import { LogicalPosition, LogicalSize, appWindow, getCurrent } from '@tauri-apps/api/window'
import { invoke } from '@tauri-apps/api'
import { listen } from '@tauri-apps/api/event'
import DoorService from '@/services/door.service'

const doorService = new DoorService()
const resultValue = ref([
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false
])
const currentRois = computed(() => doorService.rois.value)
const tempValues = reactive<string[]>([])
const logText = ref('')
const rect = ref({
  x: 0,
  y: 0,
  width: window.innerWidth,
  height: window.innerHeight
})

function inputStyle(i: number, v: string) {
  const style = {
    left: currentRois.value[i][0] + currentRois.value[i][2] + 15 + 'px',
    top: currentRois.value[i][1] + 'px',
    '--n-border-color-cus': (i < 3 || !v || /^[+\-\*\/]/.test(v)) ? '#7fe7c4' : '#e88080'
  }
  if (i > 2 && i < 11) {
    style.left = currentRois.value[i][0] - 90 - 10 + 'px'
  }
  return style
}
async function autoClick() {
  const pos = await doorService.getPosition()
  for (let i = 0; i < resultValue.value.length; i++) {
    if (!resultValue.value[i]) {
      continue
    }
    let [x, y] = doorService.gatePosition(i, pos?.width, pos?.height)
    if (pos?.x || pos?.y) {
      x = (x * pos.width + pos.x) / window.screen.width
      y = (y * pos.height + pos.y) / window.screen.height
    }
    await new Promise(res => setTimeout(res, 500))
    invoke('mouse_left_click', { x, y })
  }
  await new Promise(res => setTimeout(res, 1000))
}
async function onRecalc() {
  console.log(tempValues)
  const outputs = doorService.openDoor(tempValues || [])
  resultValue.value = resultValue.value.map(() => false)
  resultValue.value = outputs || resultValue.value
  if (resultValue.value.includes(true)) {
    logText.value = '计算完成'
    // await new Promise(res => setTimeout(res, 2000))
    // appWindow.setIgnoreCursorEvents(true)
    tempValues.splice(0, 19)
    logText.value = ''
    await autoClick()
    resultValue.value = resultValue.value.map(() => false)
    appWindow.hide()
    // setTimeout(() => {
    //   appWindow.hide()
    //   logText.value = ''
    // }, 2000)
  } else {
    logText.value = '计算失败'
    return
  }
  // setTimeout(() => {
  //   resultValue.value = resultValue.value.map(() => false)
  //   logText.value = ''
  // }, 8000)
}
function onCancel() {
  appWindow.hide()
  tempValues.splice(0, 19)
  logText.value = ''
}
onMounted(async () => {
  const pos = await doorService.getPosition()
  rect.value = pos || rect.value
  appWindow.setSize(new LogicalSize(rect.value.width, rect.value.height))
  appWindow.setPosition(new LogicalPosition(rect.value.x, rect.value.y))
  appWindow.setIgnoreCursorEvents(true)
  appWindow.hide()
  // invoke('toggle_deltool')

  listen('open-door', async () => {
    console.log('open door')
    logText.value = '计算中...'
    resultValue.value = resultValue.value.map(() => false)
    appWindow.setIgnoreCursorEvents(true)
    appWindow.show()
    try {
      const pos = await doorService.getPosition()
      rect.value = pos || rect.value
      appWindow.setSize(new LogicalSize(rect.value.width, rect.value.height))
      appWindow.setPosition(new LogicalPosition(rect.value.x, rect.value.y))
      const results = await doorService.detect()
      const outputs = await doorService.openDoor(results)
      resultValue.value = outputs || resultValue.value
      // console.log(resultValue, results)
      if (resultValue.value.includes(true)) {
        logText.value = '计算完成'
        tempValues.splice(0, 19)
        logText.value = ''
        await autoClick()
        resultValue.value = resultValue.value.map(() => false)
        appWindow.hide()
      } else {
        logText.value = '计算失败'
        tempValues.splice(0, 19, ...results)
        appWindow.setIgnoreCursorEvents(false)
      }
    } catch (e) {
      logText.value = '错误 请重试'
      console.error(e)
    }
  })

  // console.log(doorService.openDoor([
  //   '200', '440', '6',
  //   '', '+80', '+100', '-60', '-20', '-40', '*2', '-40',
  //   '/2', '/2', '', '*2', '/2', '/2', '/2', ''
  // ]))
})
</script>

<template>
  <div class="door">
    <div class="log-text">{{ logText }}</div>

    <div class="result-point" v-for="(v, i) of resultValue" :class="{ active: v }" :key="i"
      :style="{ '--left': currentRois[i + 3][0], '--top': currentRois[i + 3][1] }"></div>

    <div class="manul-input" v-if="tempValues.length">
      <div class="manul-input-item" v-for="(v, i) of tempValues" :key="i" :style="inputStyle(i, v)">
        <n-input v-model:value="tempValues[i]" size="large" />
      </div>
      <n-button type="primary" size="large" :style="inputStyle(2, '')" @click="onRecalc">重新计算</n-button>
      <n-button style="margin-left:100px" type="warning" size="large" :style="inputStyle(2, '')"
        @click="onCancel">取消</n-button>
    </div>
  </div>
</template>

<style scoped lang="less">
.door {
  position: relative;
  width: 100vw;
  height: 100vh;
  box-sizing: content-box;

  .log-text {
    position: absolute;
    color: var(--primary-color);
    top: 20px;
    right: 20px;
    font-size: 16px;
  }

  .result-point {
    position: absolute;
    left: calc(var(--left) * 1px - 12.3%);
    top: calc(var(--top) * 1px + 2.5%);
    padding: 10px 25px;
    border-radius: 5px;

    &.active {
      background: #0F0;
    }
  }

  .manul-input {
    pointer-events: all !important;
    z-index: 1000;

    &-item {
      position: absolute;
      width: 90px;
      margin-top: -8px;

      :deep(.n-input) {
        background-color: #00000066;
        .n-input__state-border {
          border: var(--n-border-hover) !important;
          border-color: var(--n-border-color-cus) !important;
        }
      }
    }

    :deep(.n-button) {
      position: absolute;
      margin-left: -3px;
      margin-top: 65px;
    }
  }
}
</style>
<style>
html,
body {
  background: transparent !important;
  background-color: transparent !important;
}
</style>